#!/usr/bin/env node
import { promises as fs } from 'node:fs'
import path from 'node:path'
import sharp from 'sharp'
import {
  mdiCodeBraces,
  mdiContentCopy,
  mdiContentCut,
  mdiContentPaste,
  mdiContentSave,
  mdiImage,
  mdiLinkVariant,
  mdiOpenInNew,
  mdiReload,
  mdiSelectAll,
  mdiTabPlus,
  mdiTranslate
} from '@mdi/js'

const OUT_DIR = path.resolve(process.cwd(), 'public/icons/menu')

const ICONS = {
  CUT: mdiContentCut,
  COPY: mdiContentCopy,
  PASTE: mdiContentPaste,
  SELECT_ALL: mdiSelectAll,
  RELOAD: mdiReload,
  OPEN_LINK: mdiOpenInNew,
  OPEN_IN_NEW_TAB: mdiTabPlus,
  COPY_LINK: mdiLinkVariant,
  COPY_IMAGE: mdiImage,
  SAVE_IMAGE_AS: mdiContentSave,
  TRANSLATE_PAGE: mdiTranslate,
  INSPECT: mdiCodeBraces
}

const THEMES = {
  dark: '#EEEEEE',
  light: '#444444'
}

const SIZES = [16, 20]

function svgString(pathD, color, size) {
  return `<?xml version="1.0" encoding="UTF-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="${color}"><path d="${pathD}"/></svg>`
}

async function ensureDir(dir) {
  await fs.mkdir(dir, { recursive: true })
}

async function main() {
  await ensureDir(OUT_DIR)
  for (const [theme, color] of Object.entries(THEMES)) {
    const themeDir = path.join(OUT_DIR, theme)
    await ensureDir(themeDir)
    for (const [key, pathD] of Object.entries(ICONS)) {
      for (const size of SIZES) {
        const svg = svgString(pathD, color, size)
        const out = path.join(themeDir, `${key.toLowerCase()}-${size}.png`)
        await sharp(Buffer.from(svg)).png({ compressionLevel: 9 }).toFile(out)
        console.log('✓', path.relative(process.cwd(), out))
      }
    }
  }
  console.log('\nDone.')
}

main().catch(error => {
  console.error(error)
  process.exit(1)
})
